package service

import (
	"errors"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"

	"gorm.io/gorm"
)

// 获取权限列表
func GetRoleInfoList(info request.QueryRole) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.SysRole{})
	var roleList []model.SysRole

	if info.RoleName != "" {
		db = db.Where("`role_name` LIKE ?", "%"+info.RoleName+"%")
	}
	if info.RoleKey != "" {
		db = db.Where("`post_name` LIKE ?", "%"+info.RoleKey+"%")
	}
	if info.Status != "" {
		db = db.Where("`status` = ?", info.Status)
	}

	_ = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&roleList).Error
	return roleList, total, err
}

// 新增权限
func CreateRole(role model.SysRole) (err error) {
	if !errors.Is(global.GVA_DB.Where("role_name = ?", role.RoleName).Error, gorm.ErrRecordNotFound) {
		return errors.New("权限名称已存在")
	}

	err = global.GVA_DB.Create(&role).Error
	return err
}

// 查询权限
func QueryRole(id uint64) (role model.SysRole, err error) {
	err = global.GVA_DB.First(&role, id).Error
	return role, err
}

// 更新权限
func UpdateRole(role model.SysRole) (err error) {
	db := global.GVA_DB.Model(&model.SysRole{}).Where("role_id = ?", role.RoleId)
	if errors.Is(db.Error, gorm.ErrRecordNotFound) {
		return errors.New("找不到对应的权限")
	}

	err = db.Updates(&role).Error
	return err
}

// 删除权限
func DeleteRole(ids []uint64) (err error) {
	var total int64
	db := global.GVA_DB

	db.Where("role_id IN", ids).First(&model.SysRoleDept{}).Count(&total)
	if total > 0 {
		return errors.New("数据不存在")
	}

	// todo 后续需要加事务删除关联表
	err = db.Where(ids).Delete(&model.SysRole{}).Error
	return err
}
